package com.gjs.freechat.server.component;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gjs.freechat.server.component.bean.UserInfo;
import com.gjs.freechat.server.dao.UserDao;
import com.gjs.freechat.server.dao.mapper.UserInfoMapper;
import com.gjs.freechat.utils.MyStringUtils;

/**
 * 用户管理组件层
 * @author alienware
 *
 */
@Service
public class UserManage {
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	private List<Map<String, Object>> avatarIcons = null;
	private List<Map<String, Object>> avatarColors = null;
	
	public UserInfo createNewUser() {
		UserInfo userInfo = new UserInfo();
		String id = MyStringUtils.getRandomString(16);
		userInfo.setId(id);
		userInfo.setUserName(id);
		userInfo.setPassword(MyStringUtils.getRandomSHA1(10));
		Map<String, Object> randAvatar = getRandomAvatar();
		//System.out.println(randAvatarIcon);
		userInfo.setAvatarIcon((String)randAvatar.get("avatarIcon"));
		userInfo.setAvatarIconName((String)randAvatar.get("avatarIconName"));
		userInfo.setAvatarColor((String) randAvatar.get("avatarColorName"));
		userInfo.setLogined(1);
		
		while (!userDao.saveNewUser(userInfo)) {
			id = MyStringUtils.getRandomString(16);
			userInfo.setId(id);
			userInfo.setUserName(id);
		}
		return userInfo;
	}
	
	private Map<String, Object> getRandomAvatar() {
		if (avatarIcons == null) {
			avatarIcons = getAllAvatarIcons();
			avatarColors = getAllAvatarColors();
		}
		//System.out.println(Arrays.toString(nickName));
		Map<String, Object> avatar = new HashMap<String, Object>();
		Map<String, Object> icon = null;
		Map<String, Object> color = null;
		try {
			icon = avatarIcons.get(RandomUtils.nextInt(avatarIcons.size()));
			color = avatarColors.get(RandomUtils.nextInt(avatarColors.size()));
			avatar.putAll(icon);
			avatar.putAll(color);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return avatar;
	}
	
//	public String[] getAvatarIcon(String[] iconName) {
//		String[] icon = new String[iconName.length];
//		for (int i = 0; i < iconName.length; i++) {
//			icon[i] = iconName[i].replaceAll(" ", "").toLowerCase();
//		}
//		return icon;
//	}
	
	public List<String> getAllInterestTags() {
		return userInfoMapper.getAllInterestTags();
	}
	public List<Map<String, Object>> getAllAvatarColors() {
		return userInfoMapper.selectAllAvatarColors();
	}
	
	public List<Map<String, Object>> getAllAvatarIcons() {
		return userInfoMapper.getAllAvatarIcons();
	}
	
	public UserInfo getUserInfoByUserName(String username) {
		return userDao.getUserInfoByUserName(username);
	}
}
